//
//  BOCNetworkImageManager.m
//  BOCImageTools
//
//  Created by LeungChaos on 16/5/11.
//  Copyright © 2016年 liang. All rights reserved.
//

#import "BOCNetworkImageManager.h"
#import <CommonCrypto/CommonCrypto.h>

#import "BOCImageDownloader.h"

NSString * MDFiveStringWithString(NSString *str);

// url转换成加密后的key
NSString * objectKeyWithUrl(NSURL *url)
{
    return MDFiveStringWithString([url absoluteString]);
}

/** 返回主线程 ***/
void
dispatch_mainQueue_safely_sync(void(^block)())
{
    if ([NSThread isMainThread]) {
        block();
    } else {
        dispatch_async(dispatch_get_main_queue(),^{
            block();
        });
    }
}

@interface BOCNetworkImageManager ()

@end

static id _instance;

@implementation BOCNetworkImageManager

+ (instancetype)sharedManager
{
    return [[self alloc]init];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            // 专门管理缓存的类
            _imageCacher = [[BOCImageCacher alloc]init];
            // 专门处理下载任务的类
            _downloader = [[BOCImageDownloader alloc]init];
        });
    }
    return self;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

- (instancetype)copyWithZone:(NSZone *)zone
{
    return _instance;
}

- (instancetype)mutableCopyWithZone:(NSZone *)zone
{
    return _instance;
}

#pragma mark - 外部方法

- (BOCImageDownloadTask *)downImageWithURL:(NSURL *)url seccess:(BOCDownloadImageSeccessBlock)seccessBlock fail:(BOCDownloadImageFailErrorBlock)errorBlock
{
    return [self downImageWithURL:url progress:nil seccess:seccessBlock fail:errorBlock];
}

- (BOCImageDownloadTask *)downImageWithURL:(NSURL *)url progress:(BOCProgressHandlerProgressBlock)progressBlock seccess:(BOCDownloadImageSeccessBlock)seccessBlock fail:(BOCDownloadImageFailErrorBlock)errorBlock
{
    return [self.downloader downImageWithURL:url
                                    progress:progressBlock
                                     seccess:^(UIImage *image, NSURLResponse *response) {
                                         
                                         if (seccessBlock) {
                                             seccessBlock(image,response);
                                         }
                                     }
                                        fail:^(NSError *error, NSURLResponse *response) {
                                            
                                            if (errorBlock) {
                                                errorBlock(error,response);
                                            }
                                        }];
}


- (void)clearAllImageCacheWithState:(void(^)(BOOL isSeccess))state
{
    [self.imageCacher clearAllImageCacheWithState:state];
}

- (void)imageCacheFileSizeBlock:(void(^)(long long size))block
{
    [self.imageCacher imageCacheFileSizeBlock:block];
}

- (void)cleanExpiredFileCompletion:(void(^)())completion
{
    [self.imageCacher cleanExpiredFileCompletion:completion];
}

- (NSString *)cacheImageFilePathWithKey:(NSURL *)key
{
    return [self.imageCacher cacheImageFilePathWithKey:key];
}


/**
 *  让url成为key 返回一张图片
 */
- (UIImage *)imageForURLkey:(NSURL *)key
{
    return [self.imageCacher imageForURLkey:key];
}

// MD5
NSString * MDFiveStringWithString(NSString *str)
{
    const char *cStr = [str UTF8String];
    if (cStr == NULL) {
        cStr = "";
    }
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02x", digest[i]];
    }
    return result;
}

@end
